package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.result.Result;
import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 角色权限检查拦截器
 * 确保HR不能访问用户界面，用户不能访问HR界面
 */
@Component
@Slf4j
public class RoleCheckInterceptor implements HandlerInterceptor {

    // HR可以访问的接口路径
    private static final List<String> HR_ALLOWED_PATHS = Arrays.asList(
            "/HR_", "/api/chat", "/api/hr", "/select_job_page", "/user/list", 
            "/add_job", "/delete_job", "/update_job", "/get_job_by_id"
    );

    // 用户可以访问的接口路径
    private static final List<String> USER_ALLOWED_PATHS = Arrays.asList(
            "/User_", "/api/chat", "/api/get_delivery_records", "/api/get_delivered_jobs_by_user",
            "/api/get_delivered_job_details", "/api/deliver_resume", "/User_get_attachment",
            "/api/upload_attachment", "/user/upload", "/select_job", "/User_login", "/User_Register"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理 OPTIONS 预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            log.info("处理 OPTIONS 预检请求: {}", request.getRequestURL());
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String url = request.getRequestURL().toString();
        log.info("角色权限检查 - 拦截请求: {}", url);

        // 获取 Authorization 头
        String authorizationHeader = request.getHeader("Authorization");
        String jwt = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
        }

        if (!StringUtils.hasLength(jwt)) {
            log.info("未携带有效token,拦截+role拦截");
            Result error = Result.notLogin();
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        try {
            // 解析JWT获取角色信息
            Claims claims = JwtUtils.parseJWT(jwt);
            String role = (String) claims.get("role");
            Integer userId = (Integer) claims.get("id");
            
            log.info("JWT解析成功 - 用户ID: {}, 角色: {}", userId, role);

            // 检查角色权限
            if (!hasPermission(url, role)) {
                log.warn("权限不足 - 用户ID: {}, 角色: {}, 请求路径: {}", userId, role, url);
                Result error = Result.accessDenied();
                String accessDenied = JSONObject.toJSONString(error);
                response.getWriter().write(accessDenied);
                return false;
            }

            log.info("权限验证通过 - 用户ID: {}, 角色: {}, 请求路径: {}", userId, role, url);
            return true;

        } catch (Exception e) {
            log.error("解析jwt失败: {}", e.getMessage());
            Result error = Result.notLogin();
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
    }

    /**
     * 检查用户是否有权限访问指定路径
     * @param url 请求URL
     * @param role 用户角色 (USER 或 HR)
     * @return true表示有权限，false表示无权限
     */
    private boolean hasPermission(String url, String role) {
        if (role == null) {
            return false;
        }

        log.info("检查权限 - URL: {}, 角色: {}", url, role);

        switch (role) {
            case "USER":
                // 检查用户是否有权限访问该路径
                boolean userHasPermission = USER_ALLOWED_PATHS.stream().anyMatch(url::contains);
                log.info("用户权限检查结果: {}", userHasPermission);
                return userHasPermission;
            case "HR":
                // 检查HR是否有权限访问该路径
                boolean hrHasPermission = HR_ALLOWED_PATHS.stream().anyMatch(url::contains);
                log.info("HR权限检查结果: {}", hrHasPermission);
                return hrHasPermission;
            default:
                log.warn("未知角色: {}", role);
                return false;
        }
    }
}
